package com.zzcy.bt_print_plugin;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.zzcy.bt_print_plugin.bean.MessageEvent;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Method;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;

/**
 * Create by dhd on
 * Describe : 蓝牙插件
 */
public class BTModule extends UniModule{
    private String TAG = "OkHttp";
    private JSONObject printJsonObject;
    private int jsonType;

    /*蓝牙搜索*/
    public static final String BLE_SCAN_SUCCESS = "20000";
    /*蓝牙连接成功*/
    public static final String BLE_CONNECT_SUCCESS = "20001";
    /*蓝牙连接失败*/
    public static final String BLE_EXCEPTION_CLOSE = "20002";
    /*蓝牙打印完成*/
    public static final String BLE_PRINT_SUCCESS = "20003";
    /*蓝牙打印失败*/
    public static final String BLE_PRINT_FAIL = "20004";
    // 搜索的回调
    private static UniJSCallback searchCallback;
    // 蓝牙连接的回调
    private static UniJSCallback connectCallback;
    // 打印机打印的回调
    private static UniJSCallback printCallback;

    /**
     * 搜索到蓝牙数据（一条一条传）
     * code命令 ： 20000
     */
    public static void invokeBluetoothData(String name, String address) {
        JSONObject data = new JSONObject();
        Log.e("OkHttp", "onSuccess invokeBluetoothData: " + address);
        if (searchCallback != null) {
            data.put("code", BLE_SCAN_SUCCESS);
            data.put("blueToothName", name);
            data.put("blueToothAddress", address);
            Log.e("OkHttp", "onSuccess invokeBluetoothData11: " + address);
            searchCallback.invokeAndKeepAlive(data);
        }
    }

    /**
     * 连接成功回调
     * type  1：连接回调
     */
    public static void connectSuccessFunc() {
        Log.e("OkHttp", "onSuccess 连接成功回调：====");
        if (connectCallback != null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", BLE_CONNECT_SUCCESS);
            jsonObject.put("message", "蓝牙连接成功");
            connectCallback.invokeAndKeepAlive(jsonObject);
        }
    }

    /**
     * 连接失败、异常断开的回调
     * type  1：连接失败
     */
    public static void connectFailFunc() {
        Log.e("OkHttp", "onSuccess connectExceptionClose 异常断开的回调：====");
        JSONObject jsonObject = new JSONObject();
        if (connectCallback != null) {
            jsonObject.put("code", BLE_EXCEPTION_CLOSE);
            jsonObject.put("message", "蓝牙连接失败");
            connectCallback.invokeAndKeepAlive(jsonObject);
        }
    }

    /**
     * 蓝牙打印成功
     */
    public static void printSuccessFunc() {
        Log.e("OkHttp", "onSuccess 蓝牙打印成功回调：====");
        if (printCallback != null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", BLE_PRINT_SUCCESS);
            jsonObject.put("message", "蓝牙开始打印");
            printCallback.invoke(jsonObject);
        }
    }

    /**
     * 蓝牙打印失败
     */
    public static void printFailFunc() {
        Log.e("OkHttp", "onSuccess 蓝牙打印失败回调：====");
        if (printCallback != null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", BLE_PRINT_FAIL);
            jsonObject.put("message", "蓝牙打印失败");
            printCallback.invoke(jsonObject);
        }
    }

    /**
     * 前端调用的第1个方法  开启权限搜索蓝牙
     */
    @UniJSMethod(uiThread = true)
    public void testAsyncFunc(JSONObject options, UniJSCallback uniJSBack) {
        Log.e("OkHttp", "testAsyncFunc 点击了蓝牙: ");
        searchCallback = uniJSBack;
        Log.e("OkHttp", "onSuccess11: ");
        if (mUniSDKInstance != null && mUniSDKInstance.getContext() instanceof Activity) {
            // 初始化蓝牙的事件
            Application applicationInner = getApplicationInner();
            Log.e("OkHttp", "onSuccess22: ");
            Intent intent = new Intent(mUniSDKInstance.getContext(), BluetoothMainActivity.class);
            mUniSDKInstance.getContext().startActivity(intent);
        }
    }

    /**
     * 前端调用的第2个方法  蓝牙连接
     */
    @UniJSMethod(uiThread = true)
    public void openBluetoothConnect(JSONObject jsonObject, UniJSCallback uniJSBack) {
        connectCallback = uniJSBack;
        if (jsonObject != null) {
            EventBus.getDefault().post(new MessageEvent<>(MessageEvent.BLUETOOTH_CONNECT_MESSAGE, jsonObject));
        }
    }

    /**
     * 打印数据
     *
     * @param callback
     * @param jsonObject
     */
    @UniJSMethod(uiThread = true)
    public void printContent(final UniJSCallback callback, JSONObject jsonObject) {
        Log.e(TAG, "调用打印接收数据：" + jsonObject.toString());
        jsonType = 1;
//        printJsonObject = jsonObject;
        printJsonObject = JSONObject.parseObject(oneJson);
        sendGetSNCMD();
    }

    /**
     * 打印数据
     *
     * @param callback
     * @param jsonObject
     */
    @UniJSMethod(uiThread = true)
    public void printContentOne(JSONObject jsonObject, UniJSCallback callback) {
        Log.e(TAG, "调用打印接收数据1：" + jsonObject.toString());
        jsonType = 1;
        printJsonObject = jsonObject;
        printCallback = callback;
        if (callback != null) {
            EventBus.getDefault().post(new MessageEvent<>(MessageEvent.BLUETOOTH_PRINTING_MESSAGE, jsonObject, jsonType + ""));
        }
        sendGetSNCMD();
    }

    /**
     * 打印数据
     *
     * @param callback
     * @param jsonObject
     */
    @UniJSMethod(uiThread = true)
    public void printContentTwo(JSONObject jsonObject, UniJSCallback callback) {
        Log.e(TAG, "调用打印接收数据2：" + jsonObject.toString());
        jsonType = 2;
        printJsonObject = jsonObject;
        printCallback = callback;
        if (callback != null) {
            EventBus.getDefault().post(new MessageEvent<>(MessageEvent.BLUETOOTH_PRINTING_MESSAGE, jsonObject, jsonType + ""));
        }
        sendGetSNCMD();
    }

    /**
     * 打印数据
     *
     * @param callback
     * @param jsonObject
     */
    @UniJSMethod(uiThread = true)
    public void printContentThree(JSONObject jsonObject, UniJSCallback callback) {
        Log.e(TAG, "调用打印接收数据3：" + jsonObject.toString());
        jsonType = 3;
        printJsonObject = jsonObject;
        printCallback = callback;
        if (callback != null) {
            EventBus.getDefault().post(new MessageEvent<>(MessageEvent.BLUETOOTH_PRINTING_MESSAGE, jsonObject, jsonType + ""));
        }
        sendGetSNCMD();
    }

    /**
     * 查询序列号，返回值通过readData()返回
     */
    public void sendGetSNCMD() {
        try {
//            PrinterHelper.WriteData(new byte[]{0x1D, 0x67, 0x39});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取数据
     */
    public boolean checkBle() {
        try {
//            byte[] buf = PrinterHelper.ReadData(1000);
            byte[] buf = new byte[]{};
            String str_sn = new String(buf);
            if (str_sn != null) {
                Log.e(TAG, "查询打印机状态1：" + str_sn);
                if (str_sn.length() <= 0) {
                    return false;
                } else {
                    //有返回，判断为打印机为连接状态
                    return true;
                }
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 通过反射方法获取Application
     *
     * @return
     */
    private Application getApplicationInner() {
        try {
            Class<?> activityThread = Class.forName("android.app.ActivityThread");
            Method currentApplication = activityThread.getDeclaredMethod("currentApplication");
            Method currentActivityThread = activityThread.getDeclaredMethod("currentActivityThread");
            Object current = currentActivityThread.invoke((Object) null);
            Object app = currentApplication.invoke(current);
            return (Application) app;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    String oneJson = "{\n" +
            "    \"title\":\"智海马私人订制抗遗忘\",\n" +
            "\"date\":\"智海马私人订制抗遗忘\",\n" +
            "\"name\":\"智海马私人订制抗遗忘\",\n" +
            "\"dateCycle\":\"智海马私人订制抗遗忘测试换行测试换行\",\n" +
            "    \"type\":1,\n" +
            "    \"data\":[\n" +
            "        {\n" +
            "            \"ChName\":\"猫1\",\n" +
            "            \"EnName\":\"C\"\n" +
            "        },{\n" +
            "            \"ChName\":\"猫2\",\n" +
            "            \"EnName\":\"C\"\n" +
            "        },{\n" +
            "            \"ChName\":\"猫3\",\n" +
            "            \"EnName\":\"C\"\n" +
            "        },{\n" +
            "            \"ChName\":\"猫4\",\n" +
            "            \"EnName\":\"C\"\n" +
            "        },{\n" +
            "            \"ChName\":\"猫5\",\n" +
            "            \"EnName\":\"C\"\n" +
            "        },{\n" +
            "            \"ChName\":\"猫10\",\n" +
            "            \"EnName\":\"C\"\n" +
            "        }\n" +
            "    ]\n" +
            "}";
    String twoJson = "{\n" +
            "    \"title\":\"智海马私人订制抗遗忘\",\n" +
            "    \"data\":[\n" +
            "        {\n" +
            "            \"ChName\":\"猫\",\n" +
            "            \"EnName\":\"Cat\"\n" +
            "        },\n" +
            "        {\n" +
            "            \"ChName\":\"猫\",\n" +
            "            \"EnName\":\"Cat\"\n" +
            "        },\n" +
            "        {\n" +
            "            \"ChName\":\"猫\",\n" +
            "            \"EnName\":\"Cat\"\n" +
            "        },\n" +
            "        {\n" +
            "            \"ChName\":\"猫\",\n" +
            "            \"EnName\":\"Cat\"\n" +
            "        },\n" +
            "        {\n" +
            "            \"ChName\":\"猫\",\n" +
            "            \"EnName\":\"Cat\"\n" +
            "        },\n" +
            "        {\n" +
            "            \"ChName\":\"猫\",\n" +
            "            \"EnName\":\"Cat\"\n" +
            "        }\n" +
            "    ]\n" +
            "}";
    String threeJson = "{\n" +
            "    \"title\":\"智海马私人订制抗遗忘\",\n" +
            "\"subheading\":\"副标题\",\n" +
            "    \"type\":3,\n" +
            "    \"data\":[\n" +
            "        {\n" +
            "            \"ChName\":\"扩展这些刻板印象对人们的影响是很大的。比如，一个穿着钉\",\n" +
            "            \"EnName\":\"These stereotypes have a strong influence on people. For example\"\n" +
            "        },{\n" +
            "            \"ChName\":\"扩展这些刻板印象对人们的影响是很大的。比如，一个穿着钉\",\n" +
            "            \"EnName\":\"These stereotypes have a strong influence on people. For example\"\n" +
            "        }\n" +
            "    ]\n" +
            "}";

}
